package cn.kgc.crowdfundingadmin.Security;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MySecutityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    UserDetailsService userDetailsService;
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        //授权
        http.authorizeRequests().antMatchers("/static/**","/index").permitAll()
                /*.antMatchers("/admin/query/for/search").hasAnyAuthority("user:get")*/


                .anyRequest().authenticated()
                .and().formLogin().loginPage("/admin/to/login/page.html").permitAll()
                .loginProcessingUrl("/admin/secutity/do/login")//指定登录处理地址，不再使用原来的控制器

                .usernameParameter("loginAcct")//指定页面参数
                .passwordParameter("userPswd")
                .defaultSuccessUrl("/admin/to/main/page.html")//登录成功页面
                .failureUrl("/admin/to/login/page.html?error=true")//登录失败跳转URL，并传参方便前端进行判断
                .and()
                .logout()
                .logoutUrl("/admin/security/logout")
                .logoutSuccessUrl("/index")
                .and()
                .csrf()
                .disable() // 禁用CSRF功能，如果不禁用，只能发post请求退出，否则报错
                .exceptionHandling().accessDeniedPage("/403")
        ;
                http.rememberMe().rememberMeParameter("remember");

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{

        //认证
       /* auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("test")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("vip1");*/
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
